/**
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import LogUtil from '../../common/baseUtil/LogUtil.js';
import WifiListModel from '../../model/wifiListImpl/WifiListModel.js';
import router from '@system.router';
import wifi from '@ohos.wifi_native_js';
import prompt from '@system.prompt';
import fetch from '@system.fetch';

let logUtil = new LogUtil();
let wifiListModel = new WifiListModel();

export default {
    data: {
        list: [],
        dialogTitle: '',
        checkStatus: false,
        intervalID: 0
    },
    onInit() {
        let status = wifiListModel.getStorageValue(); //获取wifi开关状态
        prompt.showToast({
            message: 'wifi保存的状态为' + status,
            duration: 3000
        })
        logUtil.info("onInit  wifiStatus == " + wifiListModel.getStorageValue());
        this.checkStatus = status;
        this.setWifiStatus(status);
    },
//设置wifi开关
    onChangeChecked(e) {
        this.setWifiStatus(e.checked);
        this.checkStatus = e.checked;
    },
    onItemLineClick() {
        if (!wifi.isWifiActive()) {
            prompt.showToast({
                message: '请先打开wifi',
                duration: 2000
            })
            return
        }
        fetch.fetch({
            url: "https://pipehome.snakepiperobot.com/api/getBanners",
            method: 'GET',
            success: function (response) {
                var responseData = JSON.stringify(response.data);
                prompt.showDialog({
                    title: '提示',
                    message: '返回值  = ' + responseData,
                    buttons: [
                        {
                            text: '取消',
                            color: '#666666',
                        },
                        {
                            text: '确定',
                            color: '#666666',
                        }
                    ],
                    success: function (data) {
                        switch (data.index) {
                            case 0:
                                prompt.showToast({
                                    message: '取消'
                                })
                                break;
                            case 1:
                                prompt.showToast({
                                    message: '确定'
                                })
                                break;
                        }
                    },
                });
            },
            fail: function () {
                prompt.showDialog({
                    title: '提示',
                    message: '无网络',
                    buttons: [
                        {
                            text: '确定',
                            color: '#666666',
                        }
                    ],
                    success: function (data) {
                        prompt.showToast({
                            message: '确定'
                        })
                    }
                });
            }
        });
    },
    wifiScaning() {
        let tmpDatas = [];
        setTimeout(function () {
            wifi.getScanInfos((result) => {
                var datas = JSON.parse(JSON.stringify(result));
                this.list = []
                for (var i = 0; i < datas.length; i++) {
                    var item = datas[i]
                    if (i == 0) {
                        prompt.showToast({
                            message: '刷新数据   ssid = ' + item.ssid + '  bssid = ' + item.bssid + '   securityType = ' + item.securityType
                            + '   rssi = ' + item.rssi + '   band = ' + item.band + '   frequency = ' + item.frequency + '   timestamp = ' + item.timestamp,
                            duration: 2000
                        })
                    }
                    var resource = {
                        ssid: item.ssid,
                        bssid: item.bssid,
                        securityType: item.securityType,
                        rssi: item.rssi,
                        band: item.band,
                        frequency: item.frequency,
                        timestamp: item.timestamp
                    }
                    tmpDatas.push(resource);
                }
            });
        }, 2000);
        this.list = tmpDatas;
    },
    wifiLoopScaning() {
        let tempDatas = [];
        this.stopLoopScaning();
        this.intervalID = setInterval(function () {
            wifi.getScanInfos((result) => {
                var datas = JSON.parse(JSON.stringify(result));
                this.list = []
                for (var i = 0; i < datas.length; i++) {
                    var item = datas[i]
                    //                    if (i == 0) {
                    //                        prompt.showToast({
                    //                            message: '10秒定时轮询   ssid = ' + item.ssid + '  bssid = ' + item.bssid + '   securityType = ' + item.securityType
                    //                            + '   rssi = ' + item.rssi + '   band = ' + item.band + '   frequency = ' + item.frequency + '   timestamp = ' + item.timestamp,
                    //                            duration: 2000
                    //                        })
                    //                    }
                    var resource = {
                        ssid: item.ssid,
                        bssid: item.bssid,
                        securityType: item.securityType,
                        rssi: item.rssi,
                        band: item.band,
                        frequency: item.frequency,
                        timestamp: item.timestamp
                    }
                    tempDatas.push(resource);
                }
            });
        }, 10000);
        this.list = tempDatas;
    },
    stopLoopScaning() {
        if (this.intervalID != 0) {
            clearInterval(this.intervalID);
        }
    },
//根据状态设置wifi开关
    setWifiStatus(status) {
        logUtil.info("setWifiStatus  status == " + status);
        if (status) {
            if (wifi.isWifiActive()) { //如果wifi已是打开状态
                wifi.scan();
                this.wifiScaning();
                this.wifiLoopScaning();
                return;
            }
            let openResult = wifi.enableWifi();
            logUtil.info("setWifiStatus  openResult == " + openResult);
            setTimeout(function () {
                prompt.showToast({
                    message: 'wifi打开状态 ==== ' + openResult,
                    duration: 2000
                })
                if (openResult) { //如果wifi打开成功
                    wifiListModel.setStorageValue(1);
                    wifi.scan();
                    this.wifiScaning();
                    this.wifiLoopScaning();
                } else { //如果启动wifi失败，则更新switch显示状态为false
                    this.checkStatus = false;
                    prompt.showToast({
                        message: 'wifi打开失败，请稍后再试',
                        duration: 2000
                    })
                }
            }, 1500);
        } else {
            if (wifi.isWifiActive()) {
                let closeResult = wifi.disableWifi();
                logUtil.info("setWifiStatus  closeResult ==  " + closeResult);
                setTimeout(function () {
                    prompt.showToast({
                        message: 'wifi关闭状态 ==== ' + closeResult,
                        duration: 2000
                    })
                    if (closeResult) {
                        this.list = [];
                        wifiListModel.setStorageValue(0);
                        this.stopLoopScaning();
                    } else { //如果wifi关闭失败，则更新switch显示状态为true
                        this.checkStatus = true;
                        prompt.showToast({
                            message: 'wifi关闭失败，请稍后再试',
                            duration: 2000
                        })
                    }
                }, 1500);
            }
        }
    },
//下拉刷新时重新扫描附近wifi列表信息
    onCustomPullDown(e) {
        if (e.state == 'start') {
        } else {
            if (wifi.isWifiActive) {
                wifi.scan();
                this.wifiScaning();
                this.wifiLoopScaning();
            }
        }
    },
//显示输入密码弹出框
    showDialog($idx) {
        if (this.list[$idx].securityType == 1) {
            prompt.showToast({
                message: '正在连接开放网络',
                duration: 2000
            });
            let config = {
                'ssid': this.list[$idx].ssid,
                'bssid': '',
                'preSharedKey': '',
                'isHiddenSsid': false,
                'securityType': 1
            }
            wifi.connectToDevice(config);
        } else {
            this.dialogTitle = this.list[$idx].ssid;
            this.$element('wifiDialog').show()
        }
    },
//返回
    onBackPress() {
        logUtil.info('setting wifiList onBackPress start')
        router.back();
        this.stopLoopScaning();
        logUtil.info('setting wifiList onBackPress end')
    },
    onAnnalWifi(e) {
        prompt.showToast({
            message: e.detail.message,
            duration: 2000
        })
    }
}
